/**
 * 
 */
package com.ibm.testbed.script.wizards;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.wizards.NewElementWizard;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.ibm.testbed.script.perspectives.ScriptPerspective;

/**
 * @author administrator
 * 
 */
public class NewTestbedScriptWizard extends NewElementWizard {

	
	
	private NewTestbedScriptPage page;

	/**
	 * 
	 */
	public NewTestbedScriptWizard() {
		// TODO Auto-generated constructor stub
		super();
		
		setWindowTitle("New Testbed Script");
		setDefaultPageImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(IConstants.PLUGIN_ID, "icons/testbed64.png"));
	}

	
	public void addPages(){
		
		page=new NewTestbedScriptPage();
		page.init(getSelection());
		addPage(page);
		
	}
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse
	 * .core.runtime.IProgressMonitor)
	 */
	@Override
	protected void finishPage(IProgressMonitor monitor)
			throws InterruptedException, CoreException {

		 page.finishedPage(monitor);
		 

	}
	
	
	public boolean performFinish() {

		boolean res= super.performFinish();
		if (res) {
			IResource resource;
			try {
				resource = page.getType().getResource();
				final IFile configFile = page.getConfigFile();
				if (resource != null) {
					selectAndReveal(resource);
					openResource((IFile) resource);
				}
				if(configFile != null){
					getShell().getDisplay().asyncExec(new Runnable() {
						public void run() {
							IWorkbenchPage page = PlatformUI.getWorkbench()
									.getActiveWorkbenchWindow().getActivePage();
							try {
								IDE.openEditor(page, configFile,"com.ibm.testbed.script.editor.ConfigEditorPart", true);
							} catch (PartInitException e) {
							}
						}
					});
				}
				ScriptPerspective.showScriptPerspective();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return res;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.jdt.internal.ui.wizards.NewElementWizard#getCreatedElement()
	 */
	@Override
	public IJavaElement getCreatedElement() {
		// TODO Auto-generated method stub
		return page.getType();
	}

	
}
